<?php
/**
 * Created by PhpStorm.
 * User: henry
 * Date: 2017/2/23
 * Time: 上午10:11
 */

namespace business\base\services;

use business\base\models\BspShowForestModel;
use common\cache\CacheManager;

class BspShowForestService
{
    const CACHE_LIVE_SHOW_BASIC_CATEGORY = "live_bsp_show_fores";
    const CACHE_ALL_SHOE_BASIC_CATEGORY = "all_bsp_show_fores";
    const CACHE_MAP_ALL_SHOW_BASIC_CATEGORY = "all_bsp_show_fores_map";

    /**
     * 状态:1启用，0停用
     */
    const CATEGORY_STATUS_LIVENESS = 1;
    const CATEGORY_STATUS_DEATH = 0;
    /**
     * 缓存有效时间 暂定一天
     */
    const CACHE_TIMEOUT = 86400;

    public function getCategoryModelListByCodes($codes)
    {
        if (is_null($codes)) {
            return null;
        }
        $cacheModel = $this->getEhCache(self::CACHE_LIVE_SHOW_BASIC_CATEGORY);
        if (empty($cacheModel)) {
            return null;
        }
        $categoryModelArray = [];
        foreach ($codes as $code) {
            if (!empty($cacheModel[$code])) {
                $model = $cacheModel[$code];
                array_push($categoryModelArray, $model);
            }

        }
        return $categoryModelArray;
    }

    /**
     * 获取缓存对象信息
     * @param $cacheKey
     * @return null|array
     */
    private function getEhCache($cacheKey)
    {
        $cacheModel = CacheManager::get($cacheKey);
        if (empty($cacheModel)) {
            if (strcasecmp($cacheKey, self::CACHE_LIVE_SHOW_BASIC_CATEGORY) == 0) {
                $this->loadLiveShowBasicCategoryCache();
            } else {
                if (strcasecmp($cacheKey, self::CACHE_MAP_ALL_SHOW_BASIC_CATEGORY) == 0) {
                    $this->loadAllShowBasicCategoryCache();
                }
            }
        }
        $cacheModel = CacheManager::get($cacheKey);
        if (empty($cacheModel)) {
            \Yii::info("Element is null: " . $cacheKey);
            return null;
        }
        return $cacheModel;
    }

    /**
     * 根据基础分类code获取运营分类code
     * @param $basicCategoryCode
     * @return string
     */
    public function getCategoryCodeByBasicCategoryCode($basicCategoryCode){
        return BspShowForestModel::find()
            ->select('category_code')
            ->where(['basic_forest_code'=>$basicCategoryCode])
            ->scalar();
    }

    /**
     * 将启用的运营分类存储到缓存中
     */
    private function loadLiveShowBasicCategoryCache()
    {
        $mapLiveShowBasicCategory = [];
        $model = new BspShowForestModel();
        $model->categoryStatus = self::CATEGORY_STATUS_LIVENESS;
        $bclist = $this->getCategoryList($model);
        if (!empty($bclist)) {
            foreach ($bclist as $item) {
                $mapLiveShowBasicCategory[$item->categoryCode] = $item;
            }
            foreach ($bclist as $item) {
                $parentCode = $item->parentCode;
                if ($parentCode != null && strcasecmp("", $parentCode) != 0 && strcasecmp("0", $parentCode) != 0) {
                    $parentScn = isset($mapLiveShowBasicCategory[$parentCode]) ? $mapLiveShowBasicCategory[$parentCode] : null;
                    if (!is_null($parentScn)) {
                        if (is_null($parentScn->childCategoryList)) {
                            $parentScn->childCategoryList = [];
                        }
                        if (isset($mapLiveShowBasicCategory[$item->categoryCode]) && $parentScn != null) {
                            array_push($parentScn->childCategoryList, $item);
                        }
                    }
                }
            }
            CacheManager::set(self::CACHE_LIVE_SHOW_BASIC_CATEGORY, $mapLiveShowBasicCategory, self::CACHE_TIMEOUT);
            \Yii::info("加载云平台运营分类缓存数据 loadLiveShowBasicCategoryCache 完成！");
        }
    }

    /**
     * 根据code获取运营分类
     * @param $categoryCode
     * @return BspShowForestModel
     */
    public function getCategoryByCode($categoryCode){
        return BspShowForestModel::find()
            ->where(['category_code'=>$categoryCode])
            ->one();
    }

    /**
     * 根据code获取运营分类name
     * @param $categoryCode
     * @return BspShowForestModel
     */
    public function getCategoryNameByCode($categoryCode){
        return BspShowForestModel::find()
            ->select('category_name')
            ->where(['category_code'=>$categoryCode])
            ->scalar();
    }

    /**
     * 将所有的运营分类存储到缓存中
     */
    private function loadAllShowBasicCategoryCache()
    {
        $mapAllShowBasicCategory = [];
        $bclist = $this->getCategoryList();
        if (!empty($bclist)) {
            foreach ($bclist as $item) {
                $mapAllShowBasicCategory[$item->categoryCode] = $item;
            }
            foreach ($bclist as $item) {
                $parentCode = $item->parentCode;
                if ($parentCode != null && strcasecmp("", $parentCode) != 0 && strcasecmp("0", $parentCode) != 0) {
                    $parentScn = $mapAllShowBasicCategory[$parentCode];
                    if ($parentScn != null) {
                        if (is_null($parentScn->childCategoryList)) {
                            $parentScn->childCategoryList = [];
                        }
                        if ($parentScn != null) {
                            array_push($parentScn->childCategoryList, $item);
                        }
                    }
                }
            }
        }
        CacheManager::set(self::CACHE_MAP_ALL_SHOW_BASIC_CATEGORY, $mapAllShowBasicCategory, self::CACHE_TIMEOUT);
        \Yii::info("加载云平台运营分类缓存数据 loadAllShowBasicCategoryCache 完成！");
    }

    /**
     * @param BspShowForestModel $model
     * @return array|BspShowForestModel[]
     */
    public function getCategoryList(BspShowForestModel $model = null)
    {
        $query = BspShowForestModel::find();

        if (!is_null($model)) {
            $query->andFilterWhere([
                "category_code" => $model->categoryCode,
                "category_shortname" => $model->categoryShortname,
                "category_name" => $model->categoryName,
                "parent_code" => $model->parentCode,
                "is_leaf" => $model->isLeaf,
                "category_status" => $model->categoryStatus,
                "basic_forest_code" => $model->basicForestCode,
                "directoryName" => $model->directoryName,
            ]);
        }
        $result = $query->orderBy(["display_order" => SORT_ASC])->all();
        if (!empty($result)) {
            return $result;
        }
        return [];
    }

    /**
     * 查询运营分类树接口(返回启用状态的整个运营分类树)。
     * @return array|BspShowForestModel[]
     */
    public function getCategoryRootHierarchy()
    {
        $result = [];
        $cacheModel = $this->getEhCache(self::CACHE_LIVE_SHOW_BASIC_CATEGORY);
        if (empty($cacheModel)) {
            return [];
        }
        foreach ($cacheModel as $key => $value) {
            if ($value->parentCode == null || strcasecmp("0", $value->parentCode) == 0
                || strcasecmp("", $value->parentCode) == 0
            ) {
                array_push($result, $value);
            }
        }
        return $result;
    }

    /**
     * @return null|mixed
     */
    public function getCategoryCacheModel()
    {
        return $this->getEhCache(self::CACHE_LIVE_SHOW_BASIC_CATEGORY);
    }

    /**
     * 根据2级分类获取一级目录
     * @param $level2Code
     * @return false|null|string
     */
    public function getParentDirectoryName($level2Code)
    {
        $sql = <<<SQL
          SELECT  directoryName
          FROM b2b_parameter.bsp_show_forest
          WHERE
              parent_code='0' AND
              basic_forest_code = (SELECT parent_code FROM b2b_parameter.bsp_show_forest WHERE category_code = :level2Code)
SQL;
        return \Yii::$app->getDb()->createCommand($sql, [':level2Code' => $level2Code])->queryScalar();
    }
}